﻿using NLog;
using EpubFactory.Zhuishu.Model;
using EpubFactory.Zhuishu.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EpubFactory.Zhuishu.UI
{
    public partial class TocListForm : Form
    {
        protected static readonly Logger _log = LogManager.GetLogger("tocListForm",typeof(TocListForm));
        private Action<int> callback;
        CancellationTokenSource cts;
        public TocListForm()
        {
            InitializeComponent();
        }

        private void lvSiteList_DoubleClick(object sender, EventArgs e)
        {
            if (lvSiteList.SelectedIndices.Count > 0 && callback != null)
            {
                callback(lvSiteList.SelectedIndices[0] - 1);
                if (cts != null)
                {
                    cts.Cancel();
                }
                this.Close();
            }
        }
        void PingToc(IEnumerable<TocSummmaryInfo> tocList)
        {
            this.cts = new CancellationTokenSource();
            Parallel.ForEach(tocList, new ParallelOptions() { CancellationToken = cts.Token }, (toc, loop) =>
            {
                if (cts.IsCancellationRequested)
                {
                    //cts.Cancel();
                    loop.Stop();
                }
                Stopwatch st = new System.Diagnostics.Stopwatch();
                st.Start();
                try
                {
                    HttpHelper.GET(toc.link);
                }
                catch
                {

                }
                st.Stop();
                _log.Debug("{0}:{1}ms", toc.name, st.ElapsedMilliseconds);
                if (cts.IsCancellationRequested)
                {
                    //cts.Cancel();
                    loop.Stop();
                }
                RunInMainthread(() =>
                {
                    var item = lvSiteList.FindItemWithText(toc.name);
                    item.Text = toc.name + "(" + st.ElapsedMilliseconds + " ms)";
                });
            });
        }

        private void TocListForm_Load(object sender, EventArgs e)
        {
            lvSiteList.FullRowSelect = true;
        }
        public void Show(MixTocInfo mixToc, IEnumerable<TocSummmaryInfo> tocs, Action<int> callback)
        {
            this.callback = callback;
            lvSiteList.BeginUpdate();
            //添加混合源
            ListViewItem mixTocItem = new ListViewItem();
            mixTocItem.Text = "混合源";
            mixTocItem.SubItems.Add(mixToc.chapters.Length.ToString());
            mixTocItem.SubItems.Add(mixToc.chapters[mixToc.chapters.Length - 1].title);
            mixTocItem.SubItems.Add(mixToc.updated);
            lvSiteList.Items.Add(mixTocItem);
            foreach (var toc in tocs)
            {
                ListViewItem item = new ListViewItem();
                item.Text = toc.name;
                item.SubItems.Add(toc.chaptersCount.ToString());
                item.SubItems.Add(toc.lastChapter);
                item.SubItems.Add(toc.updated);
                lvSiteList.Items.Add(item);
            }

            lvSiteList.EndUpdate();
            Task.Delay(1000).ContinueWith((m) =>
            {
                PingToc(tocs);
            });

            this.ShowDialog();

        }
        private void RunAsync(Action action)
        {
            ((Action)(delegate()
            {
                if (action != null)
                {
                    action.Invoke();
                }
            })).BeginInvoke(null, null);
        }

        private void RunInMainthread(Action action)
        {
            if (IsHandleCreated)
            {
                this.BeginInvoke((Action)(delegate()
                {
                    if (action != null)
                    {
                        action.Invoke();
                    }
                }));
            }
        }

    }
}
